package server.service;

import com.qqcommon.Message;

import java.io.IOException;
import java.io.ObjectOutputStream;
import java.net.Socket;
import java.util.ArrayList;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author wty
 * @date 2022/10/27 15:29
 * 发送离线消息和文件
 */
public class OffLineMessageThread extends Thread {
    private static ConcurrentHashMap<String, ArrayList<Message>> hashMap = new ConcurrentHashMap<>();

    /**
     * 往ConcurrentHashMap增加元素
     *
     * @param receiver
     * @param message
     */
    public static void put(String receiver, Message message) {
        // 新添加元素的时候，要新建一个Arraylist
        ArrayList<Message> list = new ArrayList<>();
        list.add(message);
        if (hashMap.containsKey(receiver)) {
            // 如果同一个人发送了多条消息，就拼接list
            list.addAll(hashMap.get(receiver));
        }
        hashMap.put(receiver, list);

    }


    @Override
    @SuppressWarnings({"all"})
    public void run() {
        while (true) {
            // 遍历所有离线用户
            ConcurrentHashMap.KeySetView<String, ArrayList<Message>> keyset = hashMap.keySet();
            for (String receiverID : keyset) {
                Socket socket = ManageServerConnectServiceThread.get(receiverID).getSocket();
                try {
                    ObjectOutputStream objectOutputStream = new ObjectOutputStream(socket.getOutputStream());
                    objectOutputStream.writeObject(hashMap.get(receiverID));
//                    for (Message messageArrayList : hashMap.get(receiverID)) {
//                        messageArrayList.setSender("离线消息<" + messageArrayList.getSender() + ">");
//                        objectOutputStream.writeObject(messageArrayList);
//                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
                // 移除元素
                hashMap.remove(receiverID);

            }

            // hashMap中没有了就不推送了
            if (hashMap.size() == 0) {
                break;
            }
        }
    }
}
